

#coding:utf-8
# -*- coding: utf-8 -*-

import itchat,time,os,shutil
from itchat.content import *
from App import App


# 应用对象
app = App.instance()

def get_nowtime():
        '''获取当前时间戳'''
        return time.localtime()

@itchat.msg_register([TEXT], isFriendChat=False, isGroupChat=False, isMpChat=False)
def open_close(msg):
    if msg['Text'] in app.getconfig('open_command'):
        app.start()
    if msg['Text'] in app.getconfig('close_command'):
        app.close()
    return

@itchat.msg_register([TEXT, PICTURE], isFriendChat=True, isGroupChat=False, isMpChat=False)
def text_reply(msg):
    '''注册消息处理--文件传输助手消息处理'''
    app = App.instance()
    # 检测回复状态和消息来源
    if app.handel_open == False: return
    if msg['ToUserName'] != 'filehelper': return
    # 处理简单的指令
    if msg['Text'] in app.getconfig('runtime_command'):
        app.printRuntimeInfo()
        return
    if msg['Text'] in app.getconfig('help_command'):
        app.printHelpInfo()
        return
    # 处理复杂指令
    # 1.确认状态
    store_path = app.getconfig('store_path')
    nowtime = get_nowtime()
    add_store_folder = time.strftime("%Y%m%d", nowtime)
    add_path = store_path + add_store_folder
    if app.status == 'WAIT':
        if msg.type == TEXT:
            if msg['Text'] in app.getconfig('add_command'):
                app.last_command = 'add_command'
                infotip = app.INFO_TIP + '请发送图片（默认按照顺序保存）'
                #准备添加到文件夹
                path_is_exists = os.path.exists(add_path)
                if not path_is_exists:
                    os.makedirs(add_path)
                gotowait = True
            elif msg['Text'] in app.getconfig('select_command'):
                app.last_command = 'select_command'
                infotip = app.INFO_TIP + '请输入日期与第几张'
                #准备接收查询参数
                gotowait = True
            else:
                infotip = 'wait error'
                gotowait = False

        if gotowait:
            app.gotopend(infotip)

    elif app.status == 'PEND':
        if msg.type == PICTURE:
            msg.download(msg.fileName)
            shutil.move(str(msg.fileName), add_path)
            pass #确定图片存储位置,存入新图片
        elif msg.type == TEXT:
            if msg['Text'] in app.getconfig('finish_command'):
                # 根据执行指令 处理指令完毕操作
                if app.last_command == 'select_command':
                    infotip = app.APP_TIP + '查询完毕'
                elif app.last_command == 'add_command':
                    count = 1
                    for file in os.listdir(add_path):
                        os.rename(os.path.join(add_path,file),os.path.join(add_path,str(count)+".png"))
                        count+=1
                    infotip = app.APP_TIP + '添加完毕'
                    # 完成添加操作
                else:
                    infotip = 'error'
                app.last_command = 'finish_command'
                app.gotowait(infotip)
            else:
                if app.last_command == 'select_command':
                 #确认参数
                    if msg['Text'].find(',') == -1:
                        infotip = app.APP_TIP + '未能识别的参数，请输入类似：20190227, 1'
                        app.msgPrint(infotip, tips=False)
                    else:
                        infotip = app.APP_TIP + '正在查询~~'
                        app.msgPrint(infotip, tips=False)
                        params = msg['Text'].split(',')
                        thefolder = params[0]
                        thefilename = params[1] + '.png'
                        filepath = store_path + thefolder + os.path.sep + thefilename
                        file_is_exists = os.path.exists(filepath)
                        if file_is_exists:
                            app.msgPrint('@img@%s'%filepath, tips=False)
                            app.gotowait('')
                        else:
                            app.msgPrint(app.APP_TIP + '所查询文件不存在')
                        # itchat.send('@fil@%s'%filepath, 'filehelper')
                        # itchat.send('@vid@%s'%filepath, 'filehelper')



# 收到好友邀请自动添加好友

@itchat.msg_register(FRIENDS)
def add_friend(msg):
  itchat.add_friend(**msg['Text']) # 该操作会自动将新好友的消息录入，不需要重载通讯录
#   itchat.send_msg('Nice to meet you!', msg['RecommendInfo']['UserName'])


# 启动程序
app.run(debug=True, hotReload=True, enableCmdQR= False)